package info.webest.media.xml;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Bookmark {

	public static final String BOOKMARK_FILE_NAME = ".bookmark.xml";

	public static String load(String folder) {

		String s, result = "";

		String fileName = folder + "/" + BOOKMARK_FILE_NAME;
		File f = new File(fileName);
		if (!f.exists())
			return null;

		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					new FileInputStream(f));

			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			while ((s = bufferedReader.readLine()) != null) {
				result += s;
			}
			bufferedReader.close();
			inputStreamReader.close();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
		return result;
	}

	public static void save(String folder, String xmlData) {

		String fileName = folder + "/" + BOOKMARK_FILE_NAME;
		File f = new File(fileName);
		OutputStreamWriter outputStreamWriter = null;
		try {
			outputStreamWriter = new OutputStreamWriter(new FileOutputStream(f));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
		try {
			bufferedWriter.write(xmlData);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			bufferedWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			outputStreamWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String write(String file, long position) {

		SimpleXML xml = new SimpleXML("bookmark");
		xml.setAttr("file", file);
		xml.setAttr("position", "" + position);

		// SimpleXML child = xml.createChild("Child");
		// child.setAttr("name", "Vasya");
		// child.setAttr("sex", "male");
		// child.setAttr("age", "5");

		// SimpleXML dog = xml.getNodeByPath("Pets\\Dog", true);
		// dog.setAttr("name", "Druzshok");
		// dog.setAttr("age", "3");

		String xmlOut = SimpleXML.saveXml(xml);
		return xmlOut;
	}

	public static BookmarkData read(String xmlData) {

		String s;
		BookmarkData bm = new BookmarkData();

		SimpleXML xml = SimpleXML.loadXml(xmlData);
		if (xml != null) {
			bm.file = xml.getAttr("file");
			s = xml.getAttr("position");
			bm.position = Integer.valueOf(s);
		}
		return bm;
	}

}
